//
//  ViewController.m
//  ThePuzzle
//
//  Created by admin on 2020/12/11.
//

#import "ViewController.h"
#import "UnitView.h"

@interface ViewController ()

@property (nonatomic, retain) UIView *whiteView;
@property (nonatomic, strong) UIView *baseView;
@property (nonatomic, strong) UILabel *showLabel;
@property (nonatomic, assign) CGFloat aUnit;
@property (nonatomic, assign) int inverseNum;

@property (nonatomic, assign) NSTimer *timer;
@property (nonatomic, copy) NSString *startTime;

- (void)exchangeView:(UIView *)view1 View:(UIView *)view2;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor cyanColor];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"智能拼图";
    [self loadViews];
    [self loadButton];
    [self auxiliaryViews];
    
    
}

- (NSString *)getCurrentTime
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
    _startTime = dateTime;
    return _startTime;
}

- (void)timerangeTimer
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date1 = [formatter dateFromString:_startTime];
    NSDate *date2 = [NSDate date];
    NSTimeInterval currentTime = [date2 timeIntervalSinceDate:date1];
    
    int hour = (int)(currentTime / 3600);
    int minute = (int)(currentTime - hour * 3600) / 60;
    int second = currentTime - hour * 3600 - minute * 60;
    
    NSString *dural = [NSString stringWithFormat:@"%d分%d秒", minute, second];
    _showLabel.text = dural;
    NSLog(@"%@", dural);
}

- (void)loadButton
{
    UIButton *startBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    startBtn.frame = CGRectMake(CGRectGetMaxX(_baseView.frame) - 130, CGRectGetMaxY(_baseView.frame) + 80, 100, 40);
    startBtn.backgroundColor = [UIColor redColor];
    [startBtn.layer setBorderWidth:2.0];// 划线宽度
    [startBtn.layer setCornerRadius:10.0];// 圆角
    [startBtn setTitle:@"开始游戏" forState:UIControlStateNormal];
    [startBtn addTarget:self action:@selector(startAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:startBtn];
    
    UIButton *tBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    tBtn.frame = CGRectMake(startBtn.frame.origin.x, startBtn.frame.origin.y + 60, 100, 40);
    tBtn.backgroundColor = [UIColor redColor];
    [tBtn.layer setBorderWidth:2.0];// 划线宽度
    [tBtn.layer setCornerRadius:10.0];// 圆角
    [tBtn setTitle:@"测试按钮" forState:UIControlStateNormal];
    [tBtn addTarget:self action:@selector(tAction:) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:tBtn];
    
}
// 临时测试按钮
- (void)tAction:(UIButton *)button
{
    NSLog(@"%@", _baseView.subviews);
    
    // 计算 _baseView.subviews 的逆序数
    for (int i = 1; i < _baseView.subviews.count - 1; i++) {
        for (int j = 0; j < i; j++) {
            
            UIView *oneView = _baseView.subviews[j];
            UIView *twoView = _baseView.subviews[i];
            
            if (oneView.tag > twoView.tag) {
                
                _inverseNum ++;
                
            }
        }
    }
    NSLog(@"目前逆序数为：%d", _inverseNum);
    _inverseNum = 0;// 清零
}

// "开始游戏"按钮的点击事件实现 ---- 主要是修复奇排列偶排列的问题，从而导致的游戏过不了问题
- (void)startAction:(UIButton *)button
{
    
    [self getCurrentTime];// 开始计时
    
    _baseView.userInteractionEnabled = YES;// 打开用户交互
    _inverseNum = 0;// 用来存放逆序数
    [button setTitle:@"重新开始" forState:UIControlStateNormal];
    
    // 随机换20次位置，打乱原来的顺序
    for (int i = 0; i < 20; i++){
        int tmp1 = arc4random() % 9 + 800;
        int tmp2 = arc4random() % 9 + 800;
        
        if (tmp1 != tmp2) {
            UIView *tmpView1 = [_baseView viewWithTag:tmp1];
            UIView *tmpView2 = [_baseView viewWithTag:tmp2];
            
            [self exchangeView:tmpView1 View:tmpView2];
            
        }
    }
    NSLog(@"%@", _baseView.subviews);
    
    // 计算 _baseView.subviews 的逆序数
    for (int i = 1; i < _baseView.subviews.count - 1; i++) {
        for (int j = 0; j < i; j++) {
            
            UIView *oneView = _baseView.subviews[j];
            UIView *twoView = _baseView.subviews[i];
            
            if (oneView.tag > twoView.tag) {
                
                _inverseNum ++;
                
            }
        }
    }
    NSLog(@"打乱图片位置之后的逆序数 = %d", _inverseNum);
    
    
    // 当逆序数为奇数，也就是排列是奇排列的时候，继续换位置直到偶排列位置
    while (_inverseNum % 2 != 0) {
        
        [self startAction:nil];break;
//        [self exchangeView:tmpView1 View:tmpView2];
        
    }
    NSLog(@"可以通关了，逆序数为：%d", _inverseNum);
}

- (void)loadViews
{
    // 基础页面，用来摆放一个个单元View
    _baseView = [[UIView alloc]initWithFrame:CGRectMake(18, 18, 339, 339)];
    _baseView.backgroundColor = [UIColor lightTextColor];
    _baseView.userInteractionEnabled = NO;// 关闭用户交互
    [self.view addSubview:_baseView];
    
    // 一次移动量
    _aUnit = _baseView.frame.size.width / 3;
    
    for (int i = 0; i < 8; i++) {
    
        UnitView *aView = [[UnitView alloc]initWithFrame:CGRectMake(_aUnit * (i % 3), _aUnit * (i / 3), _aUnit, _aUnit)];
        aView.tag = 800 + i;
        [aView myAddTarget:self action:@selector(sliding:)];
        [_baseView addSubview:aView];
        
        NSString *str = [NSString stringWithFormat:@"KungFuPanda_%d_", i];
        UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:str]];
        imageView.frame = CGRectMake(0, 0, _aUnit, _aUnit);
        [aView addSubview:imageView];
    }
    
    NSLog(@"%@", _baseView.subviews);
    
    // 白色View
    _whiteView = [[UnitView alloc]initWithFrame:CGRectMake(_aUnit * 2, _aUnit * 2, _aUnit, _aUnit)];
    _whiteView.backgroundColor = [UIColor whiteColor];_whiteView.tag = 808;
    [_baseView addSubview:_whiteView];
    
}

- (void)auxiliaryViews
{
    // 用来显示时间
    _showLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(_baseView.frame) - 120, CGRectGetMaxY(_baseView.frame) + 30, 80, 30)];
    _showLabel.backgroundColor = [UIColor lightTextColor];
    _showLabel.textAlignment = NSTextAlignmentRight;
    [self.view addSubview:_showLabel];
    
    // 用来显示原图
    UIImageView *originalImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"end.png"]];
    originalImage.frame = CGRectMake(40, CGRectGetMaxY(_baseView.frame) + 30, 100, 100);
    [self.view addSubview:originalImage];
}

// 一个单元View块儿的点击事件
- (void)sliding:(UnitView *)view
{
    // 判断哪个方向没有别的View，即可以移动的方向
    // 换frame来实现移动
    if (((view.frame.origin.x == _whiteView.frame.origin.x) &&
         (fabs(view.frame.origin.y - _whiteView.frame.origin.y) < 2 * _aUnit)) ||
        ((view.frame.origin.y == _whiteView.frame.origin.y) &&
         (fabs(view.frame.origin.x - _whiteView.frame.origin.x) < 2 * _aUnit))) {
            
            [self exchangeView:view View:_whiteView];
            
            
            NSMutableString *tagsSum = [NSMutableString string];
            for (int i = 0; i < _baseView.subviews.count; i++) {
                
                UIView *aView = _baseView.subviews[i];
                [tagsSum appendFormat:@"%ld", aView.tag - 800];
                
            }
            
            if ([tagsSum isEqualToString:@"012345678"]) {
                // 游戏结束
                _baseView.userInteractionEnabled = NO;
                UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"恭喜你!" message:@"游戏过关了" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
                [alertVC addAction:cancelAction];
                [self presentViewController:alertVC animated:YES completion:nil];
            }
            
            [self timerangeTimer];
            
            
    }
    
}

- (void)exchangeView:(UIView *)view1 View:(UIView *)view2
{
    CGRect tmpViewFrame = CGRectMake(0, 0, 0, 0);
    CGRect tmpFrame1 = view1.frame;
    CGRect tmpFrame2 = view2.frame;
    // 换两个View的frame
    tmpViewFrame = tmpFrame1;// _view4.frame
    tmpFrame1 = tmpFrame2;// view.frame
    tmpFrame2 = tmpViewFrame;// 中间变量
    view1.frame = tmpFrame1;
    view2.frame = tmpFrame2;
    // 换两个view的tag
    NSInteger tmpTag = view1.tag;
    view1.tag = view2.tag;
    view2.tag = tmpTag;
}









- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
